<?php
/**
 ****** 公共函数库 ******
 * ============================================================================
 * @Copyright (c) 2010 Iluke.cn All rights reserved.
 * @Author Luke <myluke@qq.com >
 * @version 1.0
 * ============================================================================
 */
defined('COM_PATH') or die('Restricted access!');
/**
 *
 *    返回当前IP地址
 *
 * @return int
 *
 */
function getip()
{
    if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $ip = getenv('HTTP_CLIENT_IP');
    }
    elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown'))
    {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    }
    elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown'))
    {
        $ip = getenv('REMOTE_ADDR');
    }
    elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown'))
    {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    $one = '([0-9]|[0-9]{2}|1\d\d|2[0-4]\d|25[0-5])';
    if (!@preg_match('/' . $one . '\.' . $one . '\.' . $one . '\.' . $one . '$/', $ip)) {
        $ip = '0.0.0.0';
    }
    ;
    return $ip;
}

/**
 *    返回文字长度,中文占两个字符
 * @param string $str
 * @return int
 */
function len($str)
{
    $len = strlen($str);
    $i = 0;
    while ($i < $len) {
        if (preg_match("/^[" . chr(0xa1) . "-" . chr(0xff) . "]+$/", $str[$i])) {
            $i += 2;
        } else {
            $i += 1;
        }
        $n += 1;
    }
    Return $n;
}

/**
 *
 * 过滤关键字
 * @param  string  $data //需要过滤的文字
 * @param  string  $str  //要过滤词语使用|分割。例如:
 * @return string
 *
 **/
function dirty($data)
{
    $str = '强奸|他妈的|sb|fuck';
    if (!empty($data)) {
        $strarr = explode('|', $str);
        $num = count($strarr);
        for ($i = 0; $i < $num; $i++) {
            $l = len($strarr[$i]);
            for ($j = 0; $j < $l; $j++) {
                $x .= '*';
            }
            $data = preg_replace("/$strarr[$i]/i", $x, $data); //脏话过滤
            $x = '';
        }
        return $data;
    }
}

/**
 * 检测登录是否失效
 */
function checkLogin()
{
    if (!cookie_isset('user')) {
        $_SESSION['err'] = '您的登录已经失效，请重新登录！';
        Header('HTTP/1.1 303 See Other');
        Header("Location: index.php");
        exit();
    } else {
        global $user;
        $tmpArray = explode('&', cookie_get('user'));
        $user['id'] = $tmpArray[0];
        $user['account'] = $tmpArray[1];
        $user['true_name'] = $tmpArray[2];
        $user['grade'] = $tmpArray[3];
    }
}

/**
 * 转换特殊字符为HTML实体
 *
 * @param   string $str
 * @return  string
 */
function esc_html($str)
{
    if (empty($str)) {
        return $str;
    } elseif (is_array($str)) {
        $str = array_map('esc_html', $str);
    } elseif (is_object($str)) {
        $vars = get_object_vars($str);
        foreach ($vars as $key => $data) {
            $str->{$key} = esc_html($data);
        }
    } else {
        $str = htmlspecialchars($str);
    }
    return $str;
}

/**
 * 取得返回地址
 *
 * @param string $default
 * @param bool   $back_server_referer 是否返回来路
 * @return string
 */
function referer($default = '', $back_server_referer = true)
{
    $default = $default ? $default : ROOT;
    $referer = isset($_REQUEST['referer']) ? $_REQUEST['referer'] : null;
    if ($back_server_referer) {
        if (empty($referer) && isset($_SERVER['HTTP_REFERER'])) {
            $referer = $_SERVER['HTTP_REFERER'];
        } else {
            $referer = esc_html($referer);
        }
    } else {
        if (empty($referer)) {
            $referer = $default;
        } else {
            $referer = esc_html($referer);
        }

    }

    if (strpos($referer, 'login.php') !== false) $referer = $default;
    return $referer;
}

/**
 * 创建目录
 */
function mkdirs($l1, $l2 = 0777)
{
    // $l1:dir $l2:mode
    if (!is_dir($l1)) {
        mkdirs(dirname($l1), $l2);
        return @mkdir($l1, $l2);
    }
    return true;
}

/**
 * 格式化文件单位
 */
function formatFileSize($intSizeB)
{
    //不满1MB，以KB为单位
    $TO_KB = 1024;
    $TO_MB = 1048576;
    if ($intSizeB < 1048576) {
        $fileSize = round($intSizeB / $TO_KB, 2);
        return $fileSize . 'KB';
    } else {
        $fileSize = round($intSizeB / $TO_MB, 2);
        return $fileSize . 'MB';
    }
}

/**
 * 取出单个字段名称
 *
 * @param $value  外部传入值
 * @param $field 表字段
 * @param $table 表名
 * @param $type 类型 1:为单个字段 2:所有字段
 */
function get_one($value, $field='*', $table,$type=1)
{
    global $dbo;
    $rs = $dbo->getOneRecord("id=$value", TBLPRE . $table);
    if($type==1){
       return $rs[$field];
    }elseif($type==2){
       return $rs;
    }

}

/**
 *下拉菜单输出
 * @param $userid 用户的id
 * @param $table 表名
 *
 */
function drop_down($userid, $table)
{
    global $dbo;
    return $dbo->query('select * from ' . TBLPRE . $table . ' where userid= ' . $userid . ' order by id desc');
}

/**
 *输出多个订单号
 * @param int $infoid 订单id
 * @param int $type 输出类型 1:为订单名称 2:为订单id 3:导出csv时用
 */
function output_orders($infoid, $type = 1)
{
    global $dbo;
    $orders = '';
    $rs = $dbo->query('select * from ' . TBLPRE . 'orderno where infoid=' . $infoid . ' order by id desc');
    foreach ($rs as $val) {
        if ($type == 1) {
            $orders .= $val['orderno'] . '&nbsp;&nbsp;';
        } elseif ($type == 2) {
            $orders .= $val['id'] . ',';
        }elseif ($type == 3) {
            $orders .= $val['orderno'] . "|";
        }
    }
    return $orders;
}
/***
 *格式时间函数
 *
 *
 */
function onlyShowDate($strDateTime)
{
    return substr($strDateTime, 0, 10);
}

function onlyShowTime($strDateTime)
{
    return trim(substr($strDateTime, 10));
}

function getHourFromDateTime($strDateTime)
{
    return substr(onlyShowTime($strDateTime), 0, 5);
}

function getMinFromDateTime($strDateTime)
{
    return substr(onlyShowTime($strDateTime), 3, 2);
}

/**
 *
 * 发送邮件函数
 * @param  string  $toaddress    收件人email
 * @param  string  $toname    收件人姓名
 * @param  array  $data      数据
 * @return string
 *
 * */
function sendmail($data)
{
    global $config,$shopmoelarr,$statusarr;
    $objMail = new PHPMailer();
    $objMail->IsSMTP(); // 使用SMTP方式发送
    $objMail->Host = $config['MailService']['Host']; // 您的企业邮局域名
    $objMail->SMTPAuth = $config['MailService']['SMTPAuth']; // 启用SMTP验证功能
    $objMail->Username = $config['MailService']['Username']; // 邮局用户名(请填写完整的email地址)
    $objMail->Password = $config['MailService']['Password']; // 邮局密码
    $objMail->CharSet = $config['MailService']['CharSet'];
    $objMail->From = $config['MailService']['From']; //邮件发送者email地址
    $objMail->FromName = $config['MailService']['FromName'];
    $objMail->AddAddress($data['toaddress'], $data['toname']); //收件人地址，可以替换成任何想要接收邮件的email信箱,格式是AddAddress("收件人email","收件人姓名")
    $objMail->IsHTML(true); // set email format to HTML //是否使用HTML格式


    $opFile = new iFile(COM_PATH . '/html-model/orders.html', 'r');
    $opFile->getFileData();
    $mailBody = $opFile->Data;
    foreach($data['orderhtml'] as $val){
        $orderno=output_orders($val['id'],3);
        $valarr=get_one($val['contactid'], '*', 'user_contact',2);
        $coninfo=$valarr['person'].'|tel:'.$valarr['tel'].'|cell:'.$valarr['cell'].'|fax:'.$valarr['fax'].'|email:'.$valarr['email'].'|address:'.$valarr['address'];
        if(empty($val['loadingdate'])){
            $loadingdate='';
        } else{
            $loadingdate=date("Y-m-d H:i:s",$val['loadingdate']);
        }
        if(empty($val['deliverydate'])){
            $deliverydate='';
        } else{
            $deliverydate=date("Y-m-d H:i:s",$val['deliverydate']);
        }
        $mailBody = str_replace('{person}', get_one($val['userid'], 'account', 'user'), $mailBody);
        $mailBody = str_replace('{user}', $coninfo, $mailBody);
        $mailBody = str_replace('{shopno}', $val['shopno'], $mailBody);
        $mailBody = str_replace('{orderno}', $orderno, $mailBody);
        $mailBody = str_replace('{pcs}', $val['pcs'], $mailBody);
        $mailBody = str_replace('{uint}', $val['uint'], $mailBody);
        $mailBody = str_replace('{weight}', $val['weight'], $mailBody);
        $mailBody = str_replace('{volume}', $val['volume'], $mailBody);
        $mailBody = str_replace('{readydate}',$val['readydate'], $mailBody);
        $mailBody = str_replace('{shopmodel}', $shopmoelarr[$val['shopmodel']], $mailBody);
        $mailBody = str_replace('{remark}', $val['remark'], $mailBody);
        $mailBody = str_replace('{urgremark}', $val['urgremark'], $mailBody);
        $mailBody = str_replace('{status}', $statusarr[$val['status']], $mailBody);
        $mailBody = str_replace('{loadingdate}',$loadingdate , $mailBody);
        $mailBody = str_replace('{deliverydate}', $deliverydate, $mailBody);
        $mailBody = str_replace('{shipmentremark}', $val['shipmentremark'], $mailBody);
        /*$mailBody = str_replace('{volume}', $val['volume'], $mailBody);
        $mailBody = str_replace('{volume}', $val['volume'], $mailBody);
        $mailBody = str_replace('{volume}', $val['volume'], $mailBody);
        $mailBody = str_replace('{volume}', $val['volume'], $mailBody);
        $mailBody = str_replace('{volume}', $val['volume'], $mailBody);*/
        $mailBodys.=$mailBody;
    }
    $objMail->Body = $mailBodys;
    $objMail->Subject = "Mail Order"; //邮件标题
    if (!$objMail->Send()) {
        echo "邮件发送时发生错误！<p>";
        echo "错误原因: " . $mail->ErrorInfo;
        return false;
        exit;
    } else {
        return true;
    }
}
/**
 *把utf-8编码转成gb2312
 *
 *
 */
function iconvstr($data){
	$data=str_replace(',','，',$data);
	return iconv("UTF-8","GB2312//IGNORE",$data) ;
}
?>